package com.yingran.common;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.CallSuper;
import android.support.annotation.CheckResult;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.trello.rxlifecycle2.LifecycleProvider;
import com.trello.rxlifecycle2.LifecycleTransformer;
import com.trello.rxlifecycle2.RxLifecycle;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.trello.rxlifecycle2.android.RxLifecycleAndroid;
import com.yingran.common.util.DateUtil;
import com.yingran.common.util.PermissionUtils;
import com.yingran.common.util.ToastManager;
import com.yingran.common.view.HeadBar;
import com.yingran.common.view.ResizeFrameLayout;
import com.yingran.common.view.ResizeLinearLayout;
import com.yingran.common.view.ResizeRelativeLayout;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.subjects.BehaviorSubject;


public class CommonBaseActivity extends AppCompatActivity implements LifecycleProvider<ActivityEvent> {
    private final BehaviorSubject<ActivityEvent> lifecycleSubject = BehaviorSubject.create();

    private HeadBar baseActivityHeadBar;
    private ProgressDialog progressDialog;
    private long dialogStartShowTime;
    protected Handler handler = new Handler(Looper.getMainLooper());
    protected CommonBaseActivity activity;
    protected Context context;
    private Unbinder unbinder;
    private ViewGroup containerLayout;
    protected FrameLayout stateLayout;

    protected enum Title {
        None,
        Float,
        Inner
    }

    private boolean isShowRoot() {
        return true;
    }

    protected Title titleType() {
        return Title.Inner;
    }

    @Override
    @CallSuper
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.activity = this;
        this.context = this;
        if (isShowRoot()) {
            setTranslucentStatusBar();
            ViewGroup rootLayout;
            stateLayout = new FrameLayout(context);

            baseActivityHeadBar = new HeadBar(context);
            Title title = titleType();
            if (title == Title.Inner) {

                LinearLayout tempRootLayout = new ResizeLinearLayout(context);
                tempRootLayout.setOrientation(LinearLayout.VERTICAL);
                tempRootLayout.addView(baseActivityHeadBar, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));

                containerLayout = new LinearLayout(context);
                stateLayout.addView(containerLayout, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0);
                params.weight = 1;
                tempRootLayout.addView(stateLayout, params);
                rootLayout = tempRootLayout;
            } else if (title == Title.Float) {
                rootLayout = new ResizeRelativeLayout(context);
                rootLayout.addView(stateLayout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                rootLayout.addView(baseActivityHeadBar, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                containerLayout = stateLayout;
            } else {
                rootLayout = new ResizeFrameLayout(context);
                rootLayout.addView(stateLayout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                containerLayout = stateLayout;
            }
            containerLayout.setId(View.generateViewId());
            rootLayout.setFitsSystemWindows(true);
            super.setContentView(rootLayout);
        }
        lifecycleSubject.onNext(ActivityEvent.CREATE);
    }


    @Override
    public void setContentView(int layoutResID) {
        this.setContentView(getLayoutInflater().inflate(layoutResID, null));
    }

    @Override
    public void setContentView(View view) {
        this.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        if (view != null && containerLayout != null) {
            containerLayout.removeView(view);
            containerLayout.addView(view, params);
        }
        unbinder = ButterKnife.bind(this);
    }

    @SuppressLint("MissingSuperCall")
    @Override
    protected void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
        getDelegate().onSaveInstanceState(outState);
    }

    protected HeadBar getHeadBar() {
        return baseActivityHeadBar;
    }

    @Override
    public void setTitle(CharSequence title) {
        if (title == null) {
            return;
        }
        baseActivityHeadBar.setTitle(title.toString());
    }


    protected boolean isEmpty(CharSequence msg) {
        return TextUtils.isEmpty(msg);
    }

    protected boolean isEmpty(@NonNull TextView editText) {
        return TextUtils.isEmpty(editText.getText().toString().trim());
    }

    protected boolean isNotEmpty(@NonNull TextView editText) {
        return !TextUtils.isEmpty(editText.getText().toString().trim());
    }

    protected boolean isNotEmpty(CharSequence msg) {
        return !TextUtils.isEmpty(msg);
    }

    protected boolean isSame(String msgL, String msgR) {
        return TextUtils.equals(msgL, msgR);
    }

    protected boolean isNotSame(String msgL, String msgR) {
        return !TextUtils.equals(msgL, msgR);
    }

    public void destroyActivity() {
        hideSoftInput();
        super.finish();
    }

    protected void destroyActivityWithAnimal() {
        hideSoftInput();
        super.finish();
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }


    protected void showLog(Object o) {
        if (o == null) {
            LogTool.e("Log->  NULL");
            return;
        }
        LogTool.e("Log->  " + o.toString());
    }

    private long lastClickTime;

    protected boolean isFastClick() {
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) < 1000) {
            lastClickTime = curClickTime;
            return true;
        }
        lastClickTime = curClickTime;
        return false;
    }

    public void jump2Activity(Class cls) {
        if (isFastClick()) {
            return;
        }
        if (cls != null) {
            Intent intent = new Intent(CommonBaseActivity.this, cls);
            startActivity(intent);
        }
    }


    public void jump2Activity(Class cls, int requestCode) {
        if (isFastClick()) {
            return;
        }
        if (cls != null) {
            Intent intent = new Intent(CommonBaseActivity.this, cls);
            startActivityForResult(intent, requestCode);
        }
    }

    public void jump2Activity(Intent intent, int requestCode) {
        if (isFastClick()) {
            return;
        }
        startActivityForResult(intent, requestCode);
    }

    public void jump2Activity(Intent intent) {
        if (isFastClick()) {
            return;
        }
        if (intent != null) {
            startActivity(intent);
        }
    }

    public void jump2Activity(Intent intent, Bundle bundle) {
        if (isFastClick()) {
            return;
        }
        if (intent != null) {
            startActivity(intent, bundle);
        }
    }

    @Override
    public void onBackPressed() {
        hideSoftInput();
        super.onBackPressed();
    }

    protected void showSoftInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
        }
    }

    protected void hideSoftInput() {
        try {
            View view = getCurrentFocus();
            if (view == null)
                view = new View(CommonBaseActivity.this);
            InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
            if (imm == null)
                return;
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void addFragment(Fragment fragment) {
        addFragment(containerLayout.getId(), fragment);
        if (titleType() == Title.Float) {
            baseActivityHeadBar.bringToFront();
        }
    }

    public void addFragment(int containerViewId, Fragment fragment) {
        if (fragment != null && !fragment.isAdded()) {
            getSupportFragmentManager().beginTransaction().add(containerViewId, fragment).commitAllowingStateLoss();
        }
    }

    public void showFragment(Fragment fragment) {
        if (fragment != null && fragment.isAdded())
            getSupportFragmentManager().beginTransaction().show(fragment).commitAllowingStateLoss();
    }

    public void replaceFragment(Fragment fragment) {
        replaceFragment(containerLayout.getId(), fragment);
    }

    public void replaceFragment(int layoutId, Fragment fragment) {
        if (fragment != null)
            getSupportFragmentManager().beginTransaction().replace(layoutId, fragment).commitAllowingStateLoss();
    }

    public void hideFragment(Fragment fragment) {
        if (fragment != null && fragment.isAdded())
            getSupportFragmentManager().beginTransaction().hide(fragment).commitAllowingStateLoss();
    }

    public void showToast(String msg) {
        ToastManager.getInstance().show(msg);
    }

    public void showWaiting(String msg) {
        hideSoftInput();
        String tipMsg = msg;
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(CommonBaseActivity.this);
        }
        if (isEmpty(tipMsg)) {
            tipMsg = "请稍后...";
        }
//        dialogStartShowTime = DateUtil.getCurrentTimeInMillis();
//        progressDialog.showLoading(tipMsg);
    }

    public void showWaiting() {
        showWaiting("请稍后...");
    }

    public void closeWaiting() {
        long rangeTime = DateUtil.getCurrentTimeInMillis() - dialogStartShowTime;
        if (rangeTime <= 1000) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (progressDialog != null) {
                        progressDialog.dismiss();
                    }
                }
            }, 1000 - rangeTime);
        } else {
            if (progressDialog != null) {
                progressDialog.dismiss();
            }
        }
    }


    protected void toSetting(int requestCode) {
        PermissionUtils.toAppSetting(CommonBaseActivity.this, requestCode, getPackageName());
    }

    protected void showPermissionDialog(final int requestCode, String msg) {
        NoticeDialog noticeDialog = new NoticeDialog(CommonBaseActivity.this);
        noticeDialog.setMsg(msg);
        noticeDialog.setCancelable(false);
        noticeDialog.setEnterClickListener(new NoticeDialog.EnterClickListener() {
            @Override
            public void enter(BaseDialog dialog) {
                dialog.dismiss();
                toSetting(requestCode);
            }
        });
        noticeDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        onResult4Permission(requestCode);
    }

    protected void onResult4Permission(int requestCode) {

    }


    @Override
    @NonNull
    @CheckResult
    public final Observable<ActivityEvent> lifecycle() {
        return lifecycleSubject.hide();
    }

    @Override
    @NonNull
    @CheckResult
    public final <T> LifecycleTransformer<T> bindUntilEvent(@NonNull ActivityEvent event) {
        return RxLifecycle.bindUntilEvent(lifecycleSubject, event);
    }

    @Override
    @NonNull
    @CheckResult
    public final <T> LifecycleTransformer<T> bindToLifecycle() {
        return RxLifecycleAndroid.bindActivity(lifecycleSubject);
    }


    /**
     * 设置全屏模式，并将状态栏设置为透明，支持4.4及以上系统
     */
    public void setTranslucentStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    @Override
    @CallSuper
    protected void onStart() {
        super.onStart();
        lifecycleSubject.onNext(ActivityEvent.START);
    }

    @Override
    @CallSuper
    protected void onResume() {
        super.onResume();
        lifecycleSubject.onNext(ActivityEvent.RESUME);
    }

    @Override
    @CallSuper
    protected void onPause() {
        lifecycleSubject.onNext(ActivityEvent.PAUSE);
        super.onPause();
    }

    @Override
    @CallSuper
    protected void onStop() {
        lifecycleSubject.onNext(ActivityEvent.STOP);
        super.onStop();
    }

    @Override
    @CallSuper
    protected void onDestroy() {
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
        if (unbinder != null) {
            unbinder.unbind();
        }
        lifecycleSubject.onNext(ActivityEvent.DESTROY);
        super.onDestroy();
    }


}
